package com.raindrop.utils;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 文件操作工具类
 * Created by liuhang on 2017/5/26.
 */

public class FileUtil {
    private static final int PROTECTED_LENGTH = 51200;// 输入流保护 50KB

    public static boolean deleteDir(File dir) {
        emptyDir(dir);
        // 目录此时为空，可以删除
        return dir.delete();
    }

    //清空文件夹
    public static boolean emptyDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success)
                    return false;
            }
        }
        return true;
    }

    //获取文件类型
    public static String getFileType(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    //获取文件类型
    public static String getFileName(String fileName) {
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    //文件夹的复制
    public static void copyDir(String path, String copyPath) throws IOException {
        File filePath = new File(path);
        if (filePath.isDirectory()) {
            File[] list = filePath.listFiles();
            for (int i = 0; i < list.length; i++) {
                String newPath = path + File.separator + list[i].getName();
                String newCopyPath = copyPath + File.separator + list[i].getName();
                File newFile = new File(copyPath);
                if (!newFile.exists()) newFile.mkdir();
                copyDir(newPath, newCopyPath);
            }
        } else if (filePath.isFile()) {
            copyFile(path, copyPath);
        } else {
            System.out.println("请输入正确的文件名或路径名");
        }
    }

    //复制文件
    public static void copyFile(String path, String copyPath) throws IOException {
        DataInputStream read = new DataInputStream(
                new BufferedInputStream(new FileInputStream(path)));
        DataOutputStream write = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(copyPath)));
        byte[] buf = new byte[1024 * 512];
        while (read.read(buf) != -1) {
            write.write(buf);
        }
        read.close();
        write.close();
    }

    //将文本的输入流转化为字符串
    public static String readInfoStream(InputStream input, String encoding) throws IOException {
        if (input == null) {
            throw new IOException("输入流为null");
        }
        //字节数组
        byte[] bcache = new byte[2048];
        int readSize = 0;//每次读取的字节长度
        int totalSize = 0;//总字节长度
        ByteArrayOutputStream infoStream = new ByteArrayOutputStream();
        try {
            //一次性读取2048字节
            while ((readSize = input.read(bcache)) > 0) {
                totalSize += readSize;
                if (totalSize > PROTECTED_LENGTH) {
                    throw new IOException("输入流超出50K大小限制");
                }
                //将bcache中读取的input数据写入infoStream
                infoStream.write(bcache, 0, readSize);
            }
        } catch (IOException e1) {
            throw new IOException("输入流读取异常");
        } finally {
            try {
                //输入流关闭
                input.close();
            } catch (IOException e) {
                throw new IOException("输入流关闭异常");
            }
        }

        try {
            return infoStream.toString(encoding);
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedEncodingException("输出异常");
        }
    }

    //缩放图片
    public static void zoomPicture(String inputFile, String outFile, int width, int height, boolean proportion) throws IOException {
        File f = new File(inputFile);
        BufferedImage bi = ImageIO.read(f);
        zoomPicture(bi, outFile, width, height, proportion);
    }

    //输入流缩放
    public static void zoomPicture(BufferedImage bi, String outFile, int width, int height, boolean proportion) throws IOException {
        int ratioHeight = 0, ratioWhidth = 0;
        Image image = bi.getScaledInstance(width, height, bi.SCALE_SMOOTH);
        if (proportion) {
            if ((bi.getHeight() > height) || (bi.getWidth() > width)) {
                ratioHeight = height / bi.getHeight();
                ratioWhidth = width / bi.getWidth();
                if (ratioHeight > ratioWhidth) {
                    ratioWhidth = ratioHeight;
                } else {
                    ratioHeight = ratioWhidth;
                }
            }
        } else {
            ratioWhidth = width;
            ratioHeight = height;
        }
        BufferedImage tag = new BufferedImage(ratioWhidth,
                ratioHeight, BufferedImage.TYPE_INT_RGB);
        // Image.SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的,优先级比速度高 生成的图片质量比较好 但速度慢
        tag.getGraphics().drawImage(image.getScaledInstance(ratioWhidth, ratioHeight,
                Image.SCALE_SMOOTH), 0, 0, null);
        FileOutputStream out = new FileOutputStream(outFile);
        // JPEGImageEncoder可适用于其他图片类型的转换
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(tag);
        out.close();
    }

    /**
     * 向文件中写入内容
     *
     * @param filepath 文件路径与名称
     * @param newstr   写入的内容
     * @return
     * @throws IOException
     */
    public static boolean writeFileContent(String filepath, String newstr) throws IOException {
        return writeFileContent(filepath, newstr, "UTF-8");
    }

    /**
     * 附加编码控制
     *
     * @param filepath
     * @param newstr
     * @param coding
     * @return
     * @throws IOException
     */
    public static boolean writeFileContent(String filepath, String newstr, String coding) throws IOException {
        Boolean bool = false;
        String filein = newstr + "\r\n";//新写入的行，换行
        String temp = "";

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            File file = new File(filepath);//文件路径(包括文件名称)
            //将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();

            //文件原有内容
            for (int i = 0; (temp = br.readLine()) != null; i++) {
                buffer.append(temp);
                // 行与行之间的分隔符 相当于“\n”
                buffer = buffer.append(System.getProperty("line.separator"));
            }
            buffer.append(filein);

            fos = new FileOutputStream(file);
            pw = new PrintWriter(new OutputStreamWriter(fos, coding));
            pw.write(new String(buffer.toString().getBytes(),"UTF-8"));
            pw.flush();
            bool = true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        } finally {
            //不要忘记关闭
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return bool;
    }
}
